package com.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meeting.constant.RefundRuleConstant;
import com.meeting.entity.*;
import com.meeting.exception.BusinessException;
import com.meeting.mapper.BookingOrderMapper;
import com.meeting.mapper.CustomerMapper;
import com.meeting.mapper.MeetingRoomMapper;
import com.meeting.mapper.MeetingRoomStatusMapper;
import com.meeting.model.dto.bookingorder.BookingOrderCreateRequest;
import com.meeting.model.dto.bookingorder.BookingOrderQueryRequest;
import com.meeting.model.enums.MeetingRoomStatusEnum;
import com.meeting.model.enums.OrderStatusEnum;
import com.meeting.model.enums.PaymentStatusEnum;
import com.meeting.model.vo.BookingOrderVO;
import com.meeting.service.BookingOrderService;
import com.meeting.service.PaymentRecordService;
import com.meeting.utils.BitUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

@Slf4j
@Service
public  class BookingOrderServiceImpl extends ServiceImpl<BookingOrderMapper, BookingOrder>
        implements BookingOrderService{

    @Resource
    private MeetingRoomMapper meetingRoomMapper;

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private PaymentRecordService paymentRecordService;

    @Resource
    private MeetingRoomStatusMapper meetingRoomStatusMapper;

    @Resource
    private BitUtil bitUtil;

    @Override
    public LambdaQueryWrapper<BookingOrder> getQueryWrapper(BookingOrderQueryRequest queryRequest) {
        LambdaQueryWrapper<BookingOrder> queryWrapper = new LambdaQueryWrapper<>();
        if (queryRequest == null) {
            return queryWrapper;
        }
        Long id = queryRequest.getId();
        String orderNo = queryRequest.getOrderNo();
        Long meetingRoomId = queryRequest.getMeetingRoomId();
        Long userId = queryRequest.getUserId();
        Date startTime = queryRequest.getStartTime();
        Date endTime = queryRequest.getEndTime();
        Integer status = queryRequest.getStatus();
        Double pricePerHour = queryRequest.getPricePerHour();
        Double totalAmount = queryRequest.getTotalAmount();
        Date payExpireTime = queryRequest.getPayExpireTime();
        Date cancelTime = queryRequest.getCancelTime();
        Double refundAmount = queryRequest.getRefundAmount();
        Date createTime = queryRequest.getCreateTime();

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), BookingOrder::getId, id);
        queryWrapper.eq(StringUtils.isNotBlank(orderNo), BookingOrder::getOrderNo, orderNo);
        queryWrapper.eq(ObjectUtils.isNotEmpty(meetingRoomId), BookingOrder::getMeetingRoomId, meetingRoomId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), BookingOrder::getUserId, userId);
        queryWrapper.ge(ObjectUtils.isNotEmpty(startTime), BookingOrder::getStartTime, startTime);
        queryWrapper.le(ObjectUtils.isNotEmpty(endTime), BookingOrder::getEndTime, endTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), BookingOrder::getStatus, status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(pricePerHour), BookingOrder::getPricePerHour, pricePerHour);
        queryWrapper.eq(ObjectUtils.isNotEmpty(totalAmount), BookingOrder::getTotalAmount, totalAmount);
        queryWrapper.eq(ObjectUtils.isNotEmpty(payExpireTime), BookingOrder::getPayExpireTime, payExpireTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(cancelTime), BookingOrder::getCancelTime, cancelTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(refundAmount), BookingOrder::getRefundAmount, refundAmount);
        queryWrapper.eq(ObjectUtils.isNotEmpty(createTime), BookingOrder::getCreateTime, createTime);

        return queryWrapper;
    }

    /**
     * 退款
     * @param id 订单id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean refund(Long id) throws ParseException {
        LambdaQueryWrapper<BookingOrder> queryWrapper = getQueryWrapper(new BookingOrderQueryRequest());
        queryWrapper.eq(BookingOrder::getId, id);
        BookingOrder order = this.getOne(queryWrapper);
        if (order == null) {
            throw new BusinessException(400, "订单不存在");
        }
        if (!order.getStatus().equals(OrderStatusEnum.REFUNDING.getCode())) {
            throw new BusinessException(400, "订单状态不正确，无法退款");
        }

        Date startTime = order.getStartTime();
        Date endTime = order.getEndTime();
        Date now = new Date();

        // 计算距离开始时间的小时数
        long diffInMillis = startTime.getTime() - now.getTime();
        long diffInHours = diffInMillis / (60 * 60 * 1000);

        // 计算退款金额
        double refundRate;
        if (diffInHours >= 72) {
            refundRate = 1.0; // 提前72小时退全款
        } else if (diffInHours >= 48) {
            refundRate = 0.75; // 提前48小时退75%
        } else if (diffInHours >= 24) {
            refundRate = 0.25; // 提前24小时退25%
        } else {
            throw new BusinessException(400, "距离会议开始时间不足24小时，无法退款");
        }

        double refundAmount = order.getTotalAmount() * refundRate;

        // 更新订单状态和退款金额
        order.setStatus(OrderStatusEnum.REFUNDED.getCode());
        order.setRefundAmount(refundAmount);
        order.setCancelTime(now);
        log.info("订单退款成功，退款金额：{}", refundAmount);

        boolean b = this.updateById(order);
        if (b) {
            Long meetingRoomId = order.getMeetingRoomId();
            bitUtil.setTimeBit(meetingRoomId, startTime, endTime, MeetingRoomStatusEnum.FREE.getCode());
            if (meetingRoomId != null) {
                log.info("更新会议室状态成功");
                // 创建退款记录
                // 复用之前的支付记录的一些属性
                LambdaQueryWrapper<PaymentRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(PaymentRecord::getOrderNo, order.getOrderNo());
                PaymentRecord paymentRecord = paymentRecordService.getOne(wrapper);
                if (paymentRecord == null) {
                    throw new BusinessException(400, "订单的支付记录不存在");
                }
                paymentRecord.setPaymentAmount(refundAmount);
                paymentRecord.setPaymentStatus(PaymentStatusEnum.REFUNDED.getCode());
                paymentRecord.setPaymentTime(now);
                paymentRecord.setTransactionId(UUID.randomUUID().toString());
                paymentRecordService.updateById(paymentRecord);
                log.info("创建退款记录成功");
                return true;
            } else {
                throw new BusinessException(500, "系统错误，修改会议室状态失败");
            }
        } else {
            throw new BusinessException(500, "系统错误，订单退款失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BookingOrderVO createOrder(BookingOrderCreateRequest createRequest, Long customerId) throws ParseException {

        Customer customer = customerMapper.selectById(customerId);
        if (customer == null) {
            throw new BusinessException(401, "用户未登录");
        }

        // 2. 查询会议室信息
        MeetingRoom meetingRoom = meetingRoomMapper.selectById(createRequest.getMeetingRoomId());
        if (meetingRoom == null) {
            throw new BusinessException(404, "会议室不存在");
        }

        // 3. 检查人数有没有超过会议室最大人数
        if (createRequest.getAttendees() > meetingRoom.getSeatNum()) {
            throw new BusinessException(400, "预约人数超过会议室最大人数");
        }

        // 4. 检查预约时间
        Date startTime = createRequest.getStartTime();
        Date endTime = createRequest.getEndTime();
        Date now = new Date();

        if (startTime.before(now)) {
            throw new BusinessException(400, "开始时间不能早于当前时间");
        }

        if (endTime.before(startTime)) {
            throw new BusinessException(400, "结束时间不能早于开始时间");
        }

        // 检查预约日期是否在60天内
        Calendar maxBookingDate = Calendar.getInstance();
        maxBookingDate.setTime(now);
        maxBookingDate.add(Calendar.DAY_OF_YEAR, 60);
        if (startTime.after(maxBookingDate.getTime())) {
            throw new BusinessException(400, "预约日期不能超过60天");
        }

        // 检查预约时间是否在每日8:00到21:00之间
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(startTime);
        int startHour = startCalendar.get(Calendar.HOUR_OF_DAY);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(endTime);
        int endHour = endCalendar.get(Calendar.HOUR_OF_DAY);

        if (startHour < 8 || endHour > 21) {
            throw new BusinessException(400, "预约时间必须在每日8:00到21:00之间");
        }

        boolean isSameDay = startCalendar.get(Calendar.YEAR) == endCalendar.get(Calendar.YEAR)
                && startCalendar.get(Calendar.DAY_OF_YEAR) == endCalendar.get(Calendar.DAY_OF_YEAR);

        if (!isSameDay) {
            throw new BusinessException(400, "开始时间和结束时间不在同一天");
        }

        // 判断是否有冲突
        if (bitUtil.isConflict(meetingRoom.getId(), startTime, endTime)) {
            throw new BusinessException(400, "预约时间冲突，请选择其他时间");
        }

        // 5. 计算使用时长和订单金额
        long durationMillis = endTime.getTime() - startTime.getTime();
        double hours = (double) durationMillis / (1000 * 60 * 60);
        double amount = hours * meetingRoom.getPrice();

        // 6. 创建订单
        BookingOrder order = new BookingOrder();
        order.setOrderNo(generateOrderNo());
        order.setUserId(customerId);
        order.setMeetingRoomId(meetingRoom.getId());
        order.setStartTime(startTime);
        order.setEndTime(endTime);
        order.setPricePerHour(meetingRoom.getPrice());
        order.setTotalAmount(amount);
        order.setStatus(OrderStatusEnum.PENDING_PAYMENT.getCode());
        order.setCreateTime(now);
        order.setUpdateTime(now);

        // 7. 设置支付截止时间（30分钟后）
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, 30);
        order.setPayExpireTime(calendar.getTime());

        // 8. 保存订单
        this.save(order);

        // 9. 锁定会议室
        String meetingRoomTime = bitUtil.getMeetingRoomTime(meetingRoom.getId(), startTime);

        // 10. 插入支付记录，状态为待支付
        PaymentRecord paymentRecord = new PaymentRecord();
        paymentRecord.setOrderNo(order.getOrderNo());
        paymentRecord.setPaymentAmount(order.getTotalAmount());
        paymentRecord.setPaymentStatus(PaymentStatusEnum.PENDING_PAYMENT.getCode());
        // 占位
        paymentRecord.setPaymentMethod(0);
        paymentRecord.setTransactionId(UUID.randomUUID().toString());
        paymentRecordService.save(paymentRecord);

        // 11. 返回订单VO
        BookingOrderVO orderVO = new BookingOrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setMeetingRoomName(meetingRoom.getName());

        // 设置会议室占用
        bitUtil.setTimeBit(meetingRoom.getId(), startTime, endTime, MeetingRoomStatusEnum.LOCKED.getCode());
        return orderVO;
    }

    /**
     * 支付订单
     * @param orderId 订单ID
     * @param customerId 用户Id
     * @return 是否支付成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean payOrder(Long orderId,Long customerId,Integer paymentMethod) throws ParseException {


        // 1. 查询订单
        BookingOrder order = this.getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 3. 检查订单是否属于当前客户
        if (!order.getUserId().equals(customerId)) {
            throw new BusinessException(403, "无权操作此订单");
        }

        // 4. 检查订单状态
        if (OrderStatusEnum.PENDING_PAYMENT.getCode() != order.getStatus()) {
            throw new BusinessException(400, "订单状态不正确");
        }

        // 5. 检查是否超过支付截止时间
        Date now = new Date();
        if (now.after(order.getPayExpireTime())) {
            throw new BusinessException(400, "订单已超时，请重新预订");
        }

        // 6. 更新订单状态为已支付
        order.setStatus(OrderStatusEnum.PAID.getCode());
        order.setUpdateTime(now);
        this.updateById(order);

        // 7. 更新会议室状态为已预订
        MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());
        bitUtil.setTimeBit(meetingRoom.getId(), order.getStartTime(), order.getEndTime(), MeetingRoomStatusEnum.RESERVED.getCode());
        meetingRoomMapper.updateById(meetingRoom);
        // 设置会议室占用
        bitUtil.setTimeBit(meetingRoom.getId(), order.getStartTime(), order.getEndTime(), MeetingRoomStatusEnum.RESERVED.getCode());

        // 8. 更新支付记录，状态为已支付
        PaymentRecord paymentRecord = paymentRecordService.getOne(new QueryWrapper<PaymentRecord>().eq("order_no", order.getOrderNo()));
        paymentRecord.setPaymentMethod(paymentMethod);
        paymentRecord.setPaymentStatus(PaymentStatusEnum.SUCCESS.getCode());
        paymentRecord.setTransactionId(UUID.randomUUID().toString());
        paymentRecord.setPaymentTime(now);
        paymentRecordService.updateById(paymentRecord);

        return true;
    }

    /**
     * 获取订单详情
     * @param orderId 订单ID
     * @param customerId 客户ID
     * @return BookingOrderVO
     */
    @Override
    public BookingOrderVO getOrderDetail(Long orderId,Long customerId) {

        // 1. 查询订单
        BookingOrder order = this.getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 3. 检查订单是否属于当前客户
        if (!order.getUserId().equals(customerId)) {
            throw new BusinessException(403, "无权查看此订单");
        }

        // 4. 查询会议室信息
        MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());

        // 5. 转换为VO
        BookingOrderVO orderVO = new BookingOrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setMeetingRoomName(meetingRoom.getName());

        return orderVO;
    }


    /**
     * 获取订单列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param customerId 客户id
     * @return Page
     */
    @Override
    public Page<BookingOrderVO> getOrderList(long pageNum, long pageSize,Long customerId) {

        // 1. 查询订单列表
        Page<BookingOrder> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<BookingOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookingOrder::getUserId, customerId);
        wrapper.orderByDesc(BookingOrder::getCreateTime);

        Page<BookingOrder> orderPage = this.page(page, wrapper);

        // 3. 转换为VO
        Page<BookingOrderVO> voPage = new Page<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        List<BookingOrderVO> voList = new ArrayList<>();

        for (BookingOrder order : orderPage.getRecords()) {
            BookingOrderVO vo = new BookingOrderVO();
            BeanUtils.copyProperties(order, vo);

            // 查询会议室名称
            MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());
            if (meetingRoom != null) {
                vo.setMeetingRoomName(meetingRoom.getName());
            }

            voList.add(vo);
        }

        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 处理超时订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleTimeoutOrders() throws ParseException {
        // 1. 查询所有超时未支付的订单
        LambdaQueryWrapper<BookingOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookingOrder::getStatus, OrderStatusEnum.PENDING_PAYMENT);
        wrapper.lt(BookingOrder::getPayExpireTime, new Date());

        List<BookingOrder> timeoutOrders = this.list(wrapper);
        if (timeoutOrders.isEmpty()) {
            return;
        }

        // 2. 更新订单状态为已取消
        for (BookingOrder order : timeoutOrders) {
            order.setStatus(OrderStatusEnum.EXPIRED.getCode());
            order.setCancelTime(new Date());
            order.setUpdateTime(new Date());

            // 3. 恢复会议室状态为空闲
            MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());
            bitUtil.setTimeBit(meetingRoom.getId(), order.getStartTime(), order.getEndTime(), MeetingRoomStatusEnum.FREE.getCode());
        }

        // 4. 批量更新订单
        this.updateBatchById(timeoutOrders);

        // 5. 更新支付记录状态为失败
        List<String> list = timeoutOrders.stream().map(BookingOrder::getOrderNo).toList();
        LambdaQueryWrapper<PaymentRecord> paymentRecordWrapper = new LambdaQueryWrapper<>();
        paymentRecordWrapper.in(PaymentRecord::getOrderNo, list);

        List<PaymentRecord> list1 = paymentRecordService.list(paymentRecordWrapper);
        for (PaymentRecord paymentRecord : list1) {
            paymentRecord.setPaymentStatus(PaymentStatusEnum.FAILED.getCode());
        }
        paymentRecordService.updateBatchById(list1);
    }

    @Override
    public List<BookingOrderVO> getCancellableOrders(Long customerId) {
        // 查询当前用户的所有已支付订单
        LambdaQueryWrapper<BookingOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookingOrder::getUserId, customerId);
        wrapper.eq(BookingOrder::getStatus, OrderStatusEnum.PAID.getCode());

        List<BookingOrder> orders = this.list(wrapper);
        if (orders.isEmpty()) {
            return List.of();
        }

        List<BookingOrderVO> cancellableOrders = new ArrayList<>();
        Date now = new Date();

        for (BookingOrder order : orders) {
            // 检查是否距离开始时间还有24小时
            Date startTime = order.getStartTime();
            long diffInMillis = startTime.getTime() - now.getTime();
            long diffInHours = diffInMillis / (60 * 60 * 1000);

            if (diffInHours >= 24) {
                // 转换为 VO 并添加到结果中
                BookingOrderVO vo = new BookingOrderVO();
                BeanUtils.copyProperties(order, vo);

                MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());
                if (meetingRoom != null) {
                    vo.setMeetingRoomName(meetingRoom.getName());
                }

                cancellableOrders.add(vo);
            }
        }

        return cancellableOrders;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public BookingOrderVO cancelOrder(Long orderId, Long customerId) {
        // 1. 查询订单
        BookingOrder order = this.getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 2. 检查订单是否属于当前客户
        if (!order.getUserId().equals(customerId)) {
            throw new BusinessException(403, "无权操作此订单");
        }

        // 3. 检查订单状态
        if (order.getStatus() != OrderStatusEnum.PENDING_PAYMENT.getCode() ) {
            throw new BusinessException(400, "订单状态不正确，无法取消");
        }

        // 4. 更新订单状态
        order.setStatus(OrderStatusEnum.CANCELED.getCode());

        Date now = new Date();

        order.setCancelTime(now);
        order.setUpdateTime(now);
        this.updateById(order);

        // 5. 释放会议室
        MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());


        // 6. 返回订单信息
        BookingOrderVO orderVO = new BookingOrderVO();
        BeanUtils.copyProperties(order, orderVO);
        if (meetingRoom != null) {
            orderVO.setMeetingRoomName(meetingRoom.getName());
        }

        return orderVO;

    }

    /**
     * 退款
     * @param orderId
     * @param customerId
     * @return
     */
    @Override
    public BookingOrderVO refundOrder(Long orderId, Long customerId) {
        // 1. 查询订单
        BookingOrder order = this.getById(orderId);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 2. 检查订单是否属于当前客户
        if (!order.getUserId().equals(customerId)) {
            throw new BusinessException(403, "无权操作此订单");
        }

        // 3. 检查订单状态
        if (order.getStatus() != OrderStatusEnum.PAID.getCode() ) {
            throw new BusinessException(400, "订单状态不正确，无法取消");
        }

        // 4. 检查是否满足取消条件（至少提前24小时）
        Date startTime = order.getStartTime();
        Date now = new Date();
        long diffInMillis = startTime.getTime() - now.getTime();
        long diffInHours = diffInMillis / (60 * 60 * 1000);

        if (diffInHours < 24) {
            throw new BusinessException(400, "距离会议开始时间不足24小时，无法取消预订");
        }

        // 5. 计算退款金额
        double refundRate;
        if (diffInHours >= 72) {
            refundRate = RefundRuleConstant.REFUND_RATE_72H;
        } else if (diffInHours >= 48) {
            refundRate = RefundRuleConstant.REFUND_RATE_48H;
        } else {
            refundRate = RefundRuleConstant.REFUND_RATE_24H;
        }

        double refundAmount = order.getTotalAmount() * refundRate;

        // 6. 更新订单状态
        order.setStatus(OrderStatusEnum.REFUNDING.getCode());



        order.setRefundAmount(refundAmount);
        order.setCancelTime(now);
        order.setUpdateTime(now);
        this.updateById(order);

        // 7. 释放会议室
        MeetingRoom meetingRoom = meetingRoomMapper.selectById(order.getMeetingRoomId());


        // 9. 返回订单信息
        BookingOrderVO orderVO = new BookingOrderVO();
        BeanUtils.copyProperties(order, orderVO);
        if (meetingRoom != null) {
            orderVO.setMeetingRoomName(meetingRoom.getName());
        }

        return orderVO;
    }

    /**
     * 处理已支付且已使用的订单，将它们设置为已完成状态
     */
    @Override
    public void handleUsedOrders() {
        // 查询已支付且当前时间大于结束时间的订单
        LambdaQueryWrapper<BookingOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BookingOrder::getStatus, OrderStatusEnum.PAID.getCode());
        wrapper.le(BookingOrder::getEndTime, new Date());
        List<BookingOrder> orders = this.list(wrapper);
        for (BookingOrder order : orders) {
            order.setStatus(OrderStatusEnum.COMPLETED.getCode());
        }
        this.updateBatchById(orders);
    }

    /**
     * 拒绝退款
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refuseRefund(Long id) {
        // 1. 查询订单
        BookingOrder order = this.getById(id);
        if (order == null) {
            throw new BusinessException(404, "订单不存在");
        }

        // 2. 检查订单状态
        if (order.getStatus() != OrderStatusEnum.REFUNDING.getCode()) {
            throw new BusinessException(400, "订单状态不正确，无法拒绝退款");
        }

        // 3. 更新订单状态
        order.setStatus(OrderStatusEnum.PAID.getCode());
        this.updateById(order);

        return true;
    }

    /**
     * 生成订单编号
     * @return 订单编号
     */
    private String generateOrderNo() {
        // 生成格式：年月日时分秒+6位随机数
        return String.format("%s%06d",
                new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date()),
                (int) (Math.random() * 1000000));
    }
}




